package se.lnu.axez.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPOutputStream;

import se.lnu.axez.Constants;
import se.lnu.axez.TriMesh;

/**
 * Serializes axiZ {@link TriMesh} successor from mesh file formats.
 * 
 * @author stan
 * 
 */
public final class TriMeshSerializer {
	private TriMeshSerializer() {}
	
	public static void main(String[] files) throws IOException {
		ObjLoader objLoader = new ObjLoader();
		
		for (String filePath : files) {
			File file = new File(filePath);
			if (!file.exists()) {
				System.out.println("Cannot find file " + file.getAbsolutePath());
				continue;
			}
			
			String className = getFilenameWithoutExtension(file);

			// capitalize
			className = className.substring(0, 1).toUpperCase() + className.substring(1) + "TriMesh";
			
			InputStream is = new BufferedInputStream(new FileInputStream(file));
			try {
				objLoader.loadArrays(is);
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			File outputFile = new File(file.getParent(), className + ".mesh");
			composeClass(outputFile, className, objLoader);
		}
	}

	private static void composeClass(File outputFile, String className, ObjLoader objLoader) throws IOException {
		ObjectOutputStream os = new ObjectOutputStream(new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))));
		try {
			float[] facesArray = objLoader.getFaceVertices();
			float[] normalsArray = objLoader.getFaceNormals();
			float[] uvArray = objLoader.getFaceNormals();
			int indexCount = objLoader.getFacesCount() * Constants.VERTEX_COORDINATES;
			SerializedTriMesh triMesh = new SerializedTriMesh(facesArray, normalsArray, uvArray, indexCount);
			os.writeObject(triMesh);
		} finally {
			os.close();
		}
	}

	private static String getFilenameWithoutExtension(File file) {
		int index = file.getName().lastIndexOf('.');
		if (index > 0 && index <= file.getName().length() - 2) {
			return file.getName().substring(0, index);
		}

		return "";
	}
}
